<template>
	<div>
		<el-form-item class="margin-bottom-10" label="数量总数">
			<div class="flex-start-center">
				<span v-if="pageType === 'detail' || ruleForm.auditState >= 1" class="read-only-2">{{ totalQuantity }}</span>
				<jk-number-input v-else v-model="totalQuantity" placeholder="数量总数" :disabled="isSubDialog" @input="onTotalQuantityInput" />
			</div>
		</el-form-item>
		<el-row class="margin-bottom-20 flex-start-center-wrap">
			<el-col :span="24">
				<jk-table :key="pageType + '_' + tableData.length + '_' + JSON.stringify(materialList)" :data="tableData">
					<vxe-column v-if="pageType !== 'detail'" :key="addBtnDisabled ? 'col-disabled' : 'col-enabled'" title="操作" align="center" field="operation" :width="80">
						<template slot="header">
							<el-button :key="addBtnDisabled ? 'disabled' : 'enabled'" :disabled="addBtnDisabled && !isSubDialog" size="mini" type="text" @click="onAddCsBtn">+添加</el-button>
						</template>
						<template slot-scope="scope">
							<div class="flex-center">
								<el-button slot="reference" size="mini" fixed="left" type="text" @click="onRemoveCsBtn(scope)"><span style="color: red;" class="el-icon-delete"></span></el-button>
							</div>
						</template>
					</vxe-column>
					<vxe-column title="品种编号" align="left" :min-width="180" field="productCode">
						<template slot-scope="scope">
							<span v-if="pageType === 'detail'">{{ scope.row.productName }}</span>
							<remote-search-product-input
								v-else
								placeholder="品种"
								default-stock-type="FINISHED_PRODUCT"
								only-key="productId"
								query-name="productName"
								:form-data="scope.row"
								@on-select="onSelectProductChange($event,scope.rowIndex)"
							></remote-search-product-input>
						</template>
					</vxe-column>
					<vxe-column title="批号" align="left" field="batchCode" :min-width="180">
						<template slot-scope="scope">
							<span v-if="pageType === 'detail'">{{ scope.row.batchCode }}</span>
							<remote-search-batch-code-input
								v-else
								placeholder="批号"
								only-key="batchId"
								query-name="batchCode"
								:form-data="scope.row"
								@on-select="onSelectBatchChangeOfRowItem($event, scope)"
							></remote-search-batch-code-input>
						</template>
					</vxe-column>
					<vxe-column title="色名" align="left" field="colorCode" :min-width="180">
						<template slot-scope="scope">
							<span v-if="pageType === 'detail'">{{ scope.row.colorName }}</span>
							<!--  @change="onSelectColorNumberChange($event,scope.rowIndex)" -->
							<jk-select v-else v-model="scope.row.colorCode" value-key-name="code" class="width-100-percent" size="medium" :option-list="colorList" clearable placeholder="色名" @change="onValChange($event, scope.rowIndex,['colorCode','colorCode'])" />
						</template>
					</vxe-column>
					<vxe-column title="计量单位" align="left" field="unitMeasure" :width="180">
						<template slot-scope="scope">
							<span v-if="pageType === 'detail'">{{ scope.row.unitMeasure }}</span>
							<jk-input v-else v-model="scope.row.unitMeasure" placeholder="计量单位" @blur="(val)=>onValChange(val, scope.rowIndex, 'unitMeasure')" />
						</template>
					</vxe-column>
					<vxe-column title="数量" align="left" field="number" :width="180">
						<template slot-scope="scope">
							<span v-if="pageType === 'detail'">{{ scope.row.number }}</span>
							<jk-number-input v-else v-model="scope.row.number" placeholder="数量" @change="onQtyChange($event, scope)" />
						</template>
					</vxe-column>
					<vxe-column v-if="totalQuantity" title="百分比" align="left" field="percentage" :width="180">
						<template slot-scope="scope">
							<span v-if="pageType === 'detail'">{{ scope.row.percentage }}</span>
							<jk-number-input v-else v-model="scope.row.percentage" placeholder="百分比" @change="onPercentQtyChange($event, scope)" />
						</template>
					</vxe-column>
					<vxe-column v-if="hideForm" title="支数" align="left" field="sandCount" :width="180">
						<template slot-scope="scope">
							<span v-if="pageType === 'detail'">{{ scope.row.sandCount }}</span>
							<jk-number-input v-else v-model="scope.row.sandCount" placeholder="支数" @input="(val)=>onValChange(val, scope.rowIndex, 'sandCount')" />
						</template>
					</vxe-column>
					<vxe-column v-if="hideForm" title="捻度" align="left" field="twist" :width="180">
						<template slot-scope="scope">
							<span v-if="pageType === 'detail'">{{ scope.row.twist }}</span>
							<jk-input v-else v-model="scope.row.twist" placeholder="捻度" @blur="(val)=>onValChange(val, scope.rowIndex, 'twist')" />
						</template>
					</vxe-column>
					<vxe-column v-if="hideForm" title="捻向" align="left" field="twistDirection" :width="180">
						<template slot-scope="scope">
							<el-radio-group v-model="scope.row.twistDirection" size="medium" @input="(val)=>onValChange(val, scope.rowIndex, 'twistDirection')">
								<el-radio :disabled="pageType === 'detail'" label="S">S</el-radio>
								<el-radio :disabled="pageType === 'detail'" label="F">F</el-radio>
							</el-radio-group>
						</template>
					</vxe-column>
					<vxe-column v-if="hideForm" title="并线根数" align="left" field="numberLines" :width="180">
						<template slot-scope="scope">
							<span v-if="pageType === 'detail'">{{ scope.row.numberLines }}</span>
							<jk-number-input v-else v-model="scope.row.numberLines" placeholder="并线根数" @input="(val)=>onValChange(val, scope.rowIndex, 'numberLines')" />
						</template>
					</vxe-column>
					<vxe-column v-if="hideForm && pageType !== 'detail'" title="成分按钮" align="left" :width="180">
						<template slot-scope="scope">
							<!-- <el-button size="mini" fixed="left" type="text" @click="onRowBtn(scope)">详情</el-button> -->
							<el-button size="mini" fixed="left" type="text" @click="onRowBtn(scope.row,scope.rowIndex)">选择成分</el-button>
						</template>
					</vxe-column>
				</jk-table>
			</el-col>
		</el-row>
		<checkbox-product-dialog
			:default-select-rows="tableData"
			default-stock-type="SEMI_FINISHED_PRODUCTS"
			check-key-name="productId"
			:default-category="categoryCode"
			:rule-form="ruleForm"
			:dialog-state="selectProductDialogState"
			@on-confirm="onConfirmBtnOfSelectProductDialog"
			@on-visible-change="onVisibleChangeOfSelectProductDialog"
		></checkbox-product-dialog>
		<jk-dialog-batch-item-material-list
			v-if="compositionDialogData.visible"
			ref="compositionDialog"
			:color-list="colorList"
			:rule-form="ruleForm"
			:table-data="productOrderElementItemList"
			@update-composition="onUpdateComposition"
		/>
	</div>
</template>

<script>
    import checkboxPopover from './checkbox-popover';
    import remoteSearchBatchCodeInput
        from '../../../qhPrd/productConfigCotton/components/remote-search-batch-code-input';
    import checkboxProductDialog from '../checkbox-product-dialog';
    import remoteSearchProductInput from '../remote-search-product-input';
    import JkDialogBatchItemMaterialList from './jk-dialog-batch-item-material-list';
    export default {
        name: 'BatchItemMaterialList',
        props: {
            pageType: {
                type: String,
                default: ''
            },
            materialList: {
                type: Object,
                default: () => {}
            },
            colorList: {
                type: Array,
                default() {
                    return [];
                }
            },
            ruleForm: {
                type: Object,
                default: () => {}
            },
            typeSpinning: {
                type: [Number, String],
                default: 0
            },
            isSubDialog: {
                type: Boolean,
                default: false
            }
            // totalQuantity: {
            //     type: Number,
            //     default: 0
            // }
        },
        components: {
            remoteSearchProductInput,
            checkboxPopover,
            remoteSearchBatchCodeInput,
            checkboxProductDialog,
            JkDialogBatchItemMaterialList
        },
        data() {
            return {
                compositionDialogData: {
                    visible: false,
                    rowIndex: null,
                    rowData: null
                },
                productOrderElementItemList: [],
                tableData: [],
                categoryCode: '',
                addBtnDisabled: true,
                hideForm: false,
                totalQuantity: 0,
                selectProductDialogState: false
            };
        },
        methods: {
            onTotalQuantityInput(val) {
                this.totalQuantity = val;
                this.tableData.forEach((row, index) => {
                    // 通过数量计算百分比
                    // if (row.number != null && row.number !== '') {
                    //     row.percentage = parseFloat(((row.number / val) * 100).toFixed(2));
                    // }
                    // 通过百分比计算数量
                    if (this.totalQuantity > 0 && row.percentage != null && row.percentage !== '') {
                        row.number = parseFloat(((this.totalQuantity * row.percentage) / 100).toFixed(2));
                    }
                });

                this.returnData();
            },
            onValChange(val, index, field) {
                // console.log(val, index, field, 'val,index,field');

                const row = this.tableData[index];

                if (Array.isArray(field)) {
                    // 兼容多个字段
                    field.forEach((key, i) => {
                        this.$set(row, key, Array.isArray(val) ? val[i] : val);
                    });
                } else {
                    // 兼容单字段
                    this.$set(row, field, val);
                }

                this.$set(this.tableData, index, { ...row });
                // console.log(this.tableData);
                this.returnData && this.returnData();
            },
            onRowBtn(row, rowIndex) {
                this.compositionDialogData = {
                    visible: true,
                    rowIndex,
                    rowData: row
                };
                // console.log(this.productOrderElementItemList, ' this.productOrderElementItemList ');

                this.$nextTick(() => {
                    this.$refs.compositionDialog.openCompositionDialog(this.compositionDialogData.rowData, this.compositionDialogData.rowIndex, this.productOrderElementItemList);
                });
            },
            onUpdateComposition(rowIndex, subList) {
                // console.log(rowIndex, subList, 'rowIndex, subList');
                if (!Array.isArray(subList) || !subList.length) return;
                if (Array.isArray(this.tableData) && this.tableData[rowIndex]) {
                    this.tableData[rowIndex].productOrderElementItemList = subList;
                    this.productOrderElementItemList = subList;
                }

                this.returnData();
            },
            onSelectProductChange(e, index) {
                this.onValChange([e.id, e.code, e.name], index, ['productId', 'productCode', 'productName']);
            },
            // 数量变更 => 自动计算百分比
            onQtyChange(val, scope) {
                const row = this.tableData[scope.rowIndex];
                if (this.totalQuantity > 0 && val != null && val !== '') {
                    row.percentage = parseFloat(((val / this.totalQuantity) * 100).toFixed(2));
                } else {
                    row.percentage = null;
                }

                // this.validateTotal();
                this.returnData();
            },

            // 百分比变更 => 自动计算数量
            onPercentQtyChange(val, scope) {
                const row = this.tableData[scope.rowIndex];
                if (this.totalQuantity > 0 && val != null && val !== '') {
                    row.number = parseFloat(((val / 100) * this.totalQuantity).toFixed(2));
                } else {
                    row.number = null;
                }

                // this.validateTotal();
                this.returnData();
            },

            // 校验总量和总百分比不能超过上限
            validateTotal() {
                const errors = [];

                const totalNumber = this.tableData.reduce((sum, row) => sum + (Number(row.number) || 0), 0);
                const totalPercent = this.tableData.reduce((sum, row) => sum + (Number(row.percentage) || 0), 0);

                if (totalNumber > this.totalQuantity) {
                    errors.push(`数量总和 ${totalNumber} 超出总数量 ${this.totalQuantity}`);
                }

                if (totalPercent > 100) {
                    errors.push(`百分比总和 ${totalPercent}% 超出 100%`);
                } else if (totalPercent < 100) {
                    errors.push(`百分比总和 ${totalPercent}% 小于 100%`);
                }

                this.tableData.forEach((row, i) => {
                    if ((row.number == null || row.number === '') && (row.percentage == null || row.percentage === '')) {
                        errors.push(`第 ${i + 1} 行必须填写数量或百分比之一`);
                    }
                });

                return errors;
            },
            validateBeforeSubmit() {
                const errors = this.validateTotal();
                if (errors.length) {
                    return { valid: false, errors };
                }
                return { valid: true };
            },
            // onSelectColorNumberChange(e, index) {
            //     // 为了以防万一存上
            //     const name = this.colorList.find((item) => {
            //         item.code === e;
            //     }).name;
            //     this.$set(this.tableData, index, {
            //         ...this.tableData[index],
            //         colorCode: e,
            //         colorName: name
            //     });
            // },
            onVisibleChangeOfSelectProductDialog(e) {
                this.selectProductDialogState = e;
            },
            onConfirmBtnOfSelectProductDialog(list) {
                // console.log(list, 'list');

                if (list.length) {
                    this.selectProductDialogState = false;
                    list.forEach(x => {
                        this.tableData.push({
                            productId: x.id,
                            productCode: x.code,
                            productName: x.name,
                            batchCode: this.ruleForm.batchCode || '',
                            batchId: this.ruleForm.batchId || '',
                            colorName: this.ruleForm.colorName || '',
                            colorId: this.ruleForm.colorId || '',
                            colorCode: this.ruleForm.colorCode || '',
                            // colorCode: '',
                            sandCount: this.ruleForm.yarnCount || 0,
                            twist: this.ruleForm.twist || '',
                            twistDirection: this.ruleForm.twistDirection || '',
                            unitMeasure: this.ruleForm.unitName || '',
                            number: 0, // 数量
                            percentage: 0, // 百分比
                            numberLines: 0 // 并线根数
                        });
                    });
                }
                this.returnData();
            },
            onSelectBatchChangeOfRowItem(e, scope) {
                if (Object.keys(e).length) {
                    this.$set(this.tableData[scope.rowIndex], 'batchId', e.id);
                    this.$set(this.tableData[scope.rowIndex], 'batchCode', e.batchCode);
                }
                this.returnData();
            },
            onAddCsBtn() {
                this.selectProductDialogState = true;
            },
            onRemoveCsBtn(scope) {
                this.tableData.splice(scope.rowIndex, 1);
                this.returnData();
            },
            returnData() {
                this.$emit('return-data', JSON.parse(JSON.stringify({ totalQuantity: this.totalQuantity, productOrderElementItemLists: this.tableData })));
            }
        },
        watch: {
            materialList: {
                handler(newVal) {
                    this.tableData = []; // <--- 先清空，防止数据复用错乱
                    const { totalQuantity, productOrderElementItemLists } = newVal || {};
                    this.totalQuantity = totalQuantity || 0;
                    if (productOrderElementItemLists && productOrderElementItemLists.length) {
                        this.tableData = productOrderElementItemLists.map(item => ({
                            ...item,
                            orderId: this.ruleForm.id
                        })) || [];
                    }
                },
                deep: true,
                immediate: true
            },
            typeSpinning: {
                handler(newVal) {
                    this.addBtnDisabled = !Number(newVal);
                    this.hideForm = !(Number(newVal) !== 1); // 控制列名显示/隐藏
                    // TODO:'001' 半成品 '1' 成品
                    this.categoryCode = newVal === 1 ? '001' : '1';
                },
                deep: true,
                immediate: true
            }
            // totalQuantity(newVal) {
            //     if (newVal > 0) {
            //         console.log(1111);

            //         // 总数变化时 充值数量和百分比
            //         this.tableData.forEach((row, index) => {
            //             row.percentage = row.percentage || 0;
            //             row.number = row.number || 0;
            //         });
            //     }
            // }
        }
    };
</script>
